import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Drawer, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { column } from '../../stores/definitionsSendCar';
import SendCarConfirmDialog from './SendCarConfirmDialog';
import TauActionPanel from '@/components/TauActionPanel';

const tableId = uniqueId('tauTable-');
const SendCarDrawer = (props) => {
  const {
    visible,
    onClose,
    task,
  } = props;
  const { ccTaskStore: store } = useStore();
  const driverInfoRef = useRef();
  const [modal, setModal] = useState([]);
  const [order, setOrder] = useState({});
  const [sendLoading, setSendLoading] = useState(false);
  const paramsRef = useRef(null);
  const {
    carrierCompany,
    id,
    orderIds = [],
  } = task || {};

  useEffect(() => {
    (async () => {
      if (visible) {
        await initFetch();
      }
    })();
  }, [visible]);

  /**
   * @desc
   * @param {}
   * @return {}
   */
  const initFetch = async () => {
    const data = await store.getOrderInfo(orderIds[0]);
    paramsRef.current = data;
    setOrder(toJS(data));
  };

  const handleOnSearch = (params) => {
    const { ...searchArgs } = params?.values;
    const {
      portType,
      predictBeginDate,
      predictEndDate,
    } = paramsRef.current?.ccOrder;
    // eslint-disable-next-line require-atomic-updates
    store._sendCarArgs.search = {
      companyId: carrierCompany,
      portId: portType,
      predictBeginDate,
      predictEndDate,
      ...searchArgs,
    };
  };

  // 点击派车
  const handleSendCar = (driverInfo) => {
    const sendCarInfo = _.cloneDeep(driverInfo);
    driverInfoRef.current = _.assign(sendCarInfo, { taskInfo: task, orderInfo: order });
    setModal(['sendCar']);
  };

  // 关闭确认派车弹窗
  const handleCancel = () => {
    setModal([]);
  };

  const handleSubmit = async (result) => {
    if (!_.isEmpty(result)) {
      setSendLoading(true);
      try {
        await store.sendCar(result);
        Message.success({ content: t`派车成功` });
      } catch (e) {
        Message.error({ content: t`派车失败!${e?.source?.message}`, duration: 7000 });
        throw e;
      } finally {
        setSendLoading(false);
      }
    }
    setModal([]);
    onClose();
  };

  const handleSendNotReport = () => {
    const sendCarInfo = _.cloneDeep(toJS(store._mainArgs.notReportDriver));
    driverInfoRef.current = _.assign(sendCarInfo, { taskInfo: task, orderInfo: order });
    setModal(['sendCar']);
  };

  return (
    <>
      <Drawer
        visible={visible}
        title={t`${id}派车`}
        onClose={onClose}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '90%' }}
        width="90%"
      >
        <TauActionPanel
          onSearch={handleOnSearch}
          actions={[
            {
              name: 'btn-notReport',
              title: t`未备案司机`,
              type: 'primary',
              onClick: handleSendNotReport,
            },
          ]}
          searchItems={[
          ]}
          keywordSearch={{
            placeholder: t`请输入关键字搜搜`,
          }}
          className="action-panel"
        />
        <TauTable
          instanceId={tableId}
          primaryKey="idx"
          tableLayout="fixed"
          currentPage={store._sendCarArgs.pg.page}
          pageSize={store._sendCarArgs.pg.size}
          total={store._sendCarArgs.total}
          sort={store._sendCarArgs.tableSort}
          onFetch={(pg) => { store._sendCarArgs.pg = pg; }}
          loading={store._sendCarArgs.loading}
          dataSource={toJS(store._sendCarArgs.dataSource)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store._sendCarArgs.idx(i) },
            column('fullname', { width: 58 }),
            column('showCar', { width: 100 }),
            {
              title: t`操作`,
              dataIndex: 'id',
              width: 100,
              cell: (_, __, record) => (
                <>
                  <Button
                    text
                    type="primary"
                    onClick={() => handleSendCar(record)}
                  >
                    {t`派车`}
                  </Button>
                </>
              ),
            },
          ]}
        />
      </Drawer>
      <SendCarConfirmDialog
        visible={modal[0] === 'sendCar'}
        driverInfo={driverInfoRef.current}
        onClose={handleCancel}
        onSubmit={handleSubmit}
        sendLoading={sendLoading}
      />
    </>
  );
};

export default observer(SendCarDrawer);
